﻿using System;
using System.Collections.Generic;
using Dapper;
using zhangmenren.Db;
using zhangmenren.Models;
using zhangmenren.ViewModel;
using System.Linq;

namespace zhangmenren.Repository
{
    public class ProductRepository:BaseRepository
    {

        public int Add(ProductsEntity entity)
        {
            string sql = @"INSERT INTO [Projects] 
                            ([UserId]
                            ,[Title]
                            ,AddDT)
                        VALUES
                            (@UserId
                            ,@Title
                            ,GETDATE())";
            return Execute(connection => connection.Execute(sql, entity));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns>The banner.</returns>
        public IEnumerable<ProductModel> FindByUser(int userId)
        {
            string sql = @"SELECT Id,Title,UserId,AddDT,(SELECT COUNT(Id) FROM [Item] WHERE ProductId=[Projects].Id) AS ItemNum FROM [Projects] WHERE [UserId]=@UserId ORDER BY Id DESC";
             
            return Execute(connection => connection.Query<ProductModel>(sql, new { UserId = userId }));
        }


        public IEnumerable<ProductModel> Select(int count=0)
        {
            string sql = @"SELECT Id,Title,AddDT,(SELECT COUNT(Id) FROM [Item] WHERE ProductId=[Projects].Id) AS ItemNum FROM [Projects] ORDER BY Id DESC";

            if (count > 0)
            {
                return Execute(connection => connection.Query<ProductModel>(sql)).Skip(0).Take(count);
            }
            return Execute(connection => connection.Query<ProductModel>(sql));
        }

        public int Del(int id)
        {
            string sql = @"DELETE FROM [Projects] WHERE Id = @Id";
            return Execute(connection => connection.Execute(sql, new { Id = id }));
        }

    }
}
